#include "Puck.h"

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;

const f32 Puck::RADIUS = 4.5505f;

Puck::Puck(IrrlichtDevice* device, ISceneNode* table) 
	: speed(1.f)
	, accel(0.005f)
	, maxSpeed(3.f)
{
	//driver = device->getVideoDriver();
	smgr = device->getSceneManager();

	IMesh* mesh = smgr->getMesh(L"Data/Models/shayba.obj");
	ITriangleSelector* selector = 0;

	node = smgr->addMeshSceneNode(mesh,
		table, -1, 
		vector3df(0.f, Table::SIZE.Y, 0.f));
	
	selector = smgr->createTriangleSelector(mesh, node);

	node->setMaterialType(EMT_LIGHTMAP);
	node->setTriangleSelector(selector);
}

Puck::~Puck(void)
{
}

void Puck::update()
{
	vector3df lastPosition = node->getPosition();
	vector3df position = node->getPosition();

	// 1st player field borders
	if (position.X > (Table::SIZE.X/2 - RADIUS))
	{
		direction.X = -direction.X;
		position.X = Table::SIZE.X/2 - RADIUS;
	}
	if (position.Z > (Table::SIZE.Z/2 - RADIUS))
	{
		direction.Z = -direction.Z;
		position.Z = Table::SIZE.Z/2 - RADIUS;
	}

	// 2nd player field borders
	if (position.X < (RADIUS - Table::SIZE.X/2))
	{
		direction.X = -direction.X;
		position.X = RADIUS - Table::SIZE.X/2;
	}
	if (position.Z < (RADIUS - Table::SIZE.Z/2))
	{
		direction.Z = -direction.Z;
		position.Z = RADIUS - Table::SIZE.Z/2;
	}

	node->setPosition(position + speed * direction.normalize());

	// Reduce speed
	if (speed > accel)
		speed -= accel;
	else
		speed = 0;
}

void Puck::setCollisionResult(vector3df& result, f32 clubSpeed)
{
	direction += result;
	
	if (clubSpeed > speed)
	{
		if (clubSpeed > maxSpeed)
			speed = maxSpeed;
		else
			speed = clubSpeed;
	}
}